package com.tianji.learning.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tianji.api.client.user.UserClient;
import com.tianji.api.dto.user.UserDTO;
import com.tianji.common.domain.dto.PageDTO;
import com.tianji.common.utils.AssertUtils;
import com.tianji.common.utils.CollUtils;
import com.tianji.common.utils.UserContext;
import com.tianji.learning.domain.dto.ReplyDTO;
import com.tianji.learning.domain.entity.InteractionQuestion;
import com.tianji.learning.domain.entity.InteractionReply;
import com.tianji.learning.domain.query.ReplyPageQuery;
import com.tianji.learning.domain.vo.ReplyVO;
import com.tianji.learning.mapper.InteractionReplyMapper;
import com.tianji.learning.service.IInteractionQuestionService;
import com.tianji.learning.service.IInteractionReplyService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 互动问题的回答或评论 服务实现类
 * </p>
 *
 * @author author
 */
@Service
public class InteractionReplyServiceImpl extends ServiceImpl<InteractionReplyMapper, InteractionReply> implements IInteractionReplyService {
    @Autowired
    private UserClient userClient;
    @Autowired
    @Lazy
    private IInteractionQuestionService interactionQuestionService;

    @Override
    public PageDTO<ReplyVO> queryReplyPage(ReplyPageQuery query) {
        Page<InteractionReply> page = query.toMpPage("create_time", false);
        LambdaQueryWrapper<InteractionReply> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InteractionReply::getQuestionId, query.getQuestionId());
        queryWrapper.eq(query.getAnswerId() != null, InteractionReply::getAnswerId, query.getAnswerId());
        queryWrapper.eq(InteractionReply::getHidden, false);
        this.page(page, queryWrapper);
        List<InteractionReply> records = page.getRecords();
        if (CollUtils.isEmpty(records)) {
            return PageDTO.empty(page);
        }
        //要查询的user
        List<Long> userIds = new ArrayList<>();
        List<Long> userIds1 = records.stream().map(InteractionReply::getUserId).collect(Collectors.toList());
        if (CollUtils.isNotEmpty(userIds1)){
            userIds.addAll(userIds1);
        }
        List<Long> userIds2 = records.stream().map(InteractionReply::getTargetUserId).collect(Collectors.toList());
        if (CollUtils.isNotEmpty(userIds2)){
            userIds.addAll(userIds2);
        }
        List<Long> userIds3 = records.stream().map(InteractionReply::getTargetReplyId).collect(Collectors.toList());
        if (CollUtils.isNotEmpty(userIds3)){
            userIds.addAll(userIds3);
        }
        List<UserDTO> userDTOS = userClient.queryUserByIds(userIds);
        AssertUtils.isNotNull(userDTOS, "未查询到用户信息不存在");
        Map<Long, UserDTO> userDtoMap = userDTOS.stream().collect(Collectors.toMap(UserDTO::getId, Function.identity()));
        List<ReplyVO> voList=new ArrayList<>();
        for (InteractionReply interactionReply : records) {
            ReplyVO replyVO = BeanUtil.copyProperties(interactionReply, ReplyVO.class);
            if (interactionReply.getAnonymity()){
                replyVO.setUserName("匿名用户");
            }else {
                replyVO.setUserName(userDtoMap.get(interactionReply.getUserId()).getUsername());
                replyVO.setUserIcon(userDtoMap.get(interactionReply.getUserId()).getIcon());
            }
            replyVO.setTargetUserName(userDtoMap.get(interactionReply.getTargetUserId()).getUsername());
            voList.add(replyVO);
        }
        return PageDTO.of(page, voList);
    }

    @Override
    @Transactional
    public void saveInteractionReply(ReplyDTO dto) {
        Long userId = UserContext.getUser();
        Long questionId = dto.getQuestionId();
        InteractionReply reply = new InteractionReply();
        reply.setQuestionId(questionId);
        reply.setUserId(userId);
        reply.setContent(dto.getContent());
        reply.setReplyTimes(0);
        reply.setLikedTimes(0);
        reply.setTargetUserId(dto.getTargetUserId());
        reply.setAnonymity(dto.getAnonymity());
        LocalDateTime now = LocalDateTime.now();
        reply.setCreateTime(now);
        reply.setUpdateTime(now);
        reply.setTargetReplyId(dto.getTargetReplyId()!=null?dto.getTargetReplyId():null);
        reply.setAnswerId(dto.getAnswerId()!=null?dto.getAnswerId():null);
        save(reply);
        if (dto.getAnswerId()==null){
            InteractionQuestion questionDB = interactionQuestionService.getById(questionId);
            questionDB.setLatestAnswerId(reply.getId());
            questionDB.setAnswerTimes(questionDB.getAnswerTimes()+1);
            questionDB.setUpdateTime(now);
            interactionQuestionService.updateById(questionDB);
        }else {
            Long targetReplyId = dto.getTargetReplyId();
            InteractionReply byId = getById(targetReplyId);
            byId.setReplyTimes(byId.getReplyTimes()+1);
            byId.setUpdateTime(now);
            this.updateById(byId);
        }

    }
}
